package net.keebook.webapp.ws;

import java.io.IOException;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;

import net.keebook.webapp.dao.AccountConfirmationDao;
import net.keebook.webapp.dao.SettingDao;
import net.keebook.webapp.entity.AccountConfirmation;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.util.Messages;
import net.keebook.webapp.util.SettingId;

import org.apache.log4j.Logger;


@Path("/confirm/{id}")
@Stateless
public class ConfirmAccountService extends WebService {
	@EJB
	private SettingDao settingDao;
	@Inject
	private AccountConfirmationDao accountConfirmationDao;
	
	@GET
	public void saveSettings(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("id") String confirmationId) throws IOException {
		String root = getSettingDao().get(SettingId.PUBLIC_URL).getValue();
		if (!root.endsWith("/")) {
			root += "/";
		}
		
		AccountConfirmation confirmation = getAccountConfirmationDao().get(confirmationId);
		if (confirmation == null) {
			Logger.getLogger(this.getClass()).warn("Tried to process invalid account confirmation id: " + confirmationId);
			response.sendRedirect(root + "login.xhtml?msg="+Messages.ACCOUNT_CONFIRMATION_FAILED);
		} else {
			User user = confirmation.getUser();
			if (user != null) {
				user.setConfirmed(true);
				getUserDao().update(user);
				getAccountConfirmationDao().delete(confirmation);
				
				Logger.getLogger(this.getClass()).info("Successfully processed account confirmation id: " + confirmationId);
				Logger.getLogger(this.getClass()).info("User account is now confirmed: " + user.getId());
				response.sendRedirect(root + "login.xhtml?msg="+Messages.ACCOUNT_CONFIRMED);
			} else {
				response.sendRedirect(root + "login.xhtml?msg="+Messages.ACCOUNT_CONFIRMATION_FAILED);
			}
		}
	}

	public SettingDao getSettingDao() {
		return settingDao;
	}

	public void setSettingDao(SettingDao settingDao) {
		this.settingDao = settingDao;
	}

	public AccountConfirmationDao getAccountConfirmationDao() {
		return accountConfirmationDao;
	}

	public void setAccountConfirmationDao(AccountConfirmationDao accountConfirmationDao) {
		this.accountConfirmationDao = accountConfirmationDao;
	}
}
